<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\user\model\Language as LanguageModel;
use think\Db;
/**
 * 演示文稿控制器
 * @package app\user\admin
 */
class Language extends Admin
{
    /**
     * 演示文稿列表
     * @author 李洪波 <361951119@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $data_list = LanguageModel::where($this->getMap())
            ->order($this->getOrder('id ASC'))
            ->paginate();

        $setting_btn=[
            'title'=>'一键更新',
            'icon'=>'fa fa-fw fa-key',
            'href'=>url('setting')
        ];
        return ZBuilder::make('table')
            ->setTableName('admin_language')
            ->addTopButton('add')
            ->addTopButton('delete')
            ->addRightButton('edit')
            ->addRightButton('delete')
            ->addTopButton('custom',$setting_btn)
            ->addColumns([
                ['id', 'ID'],
                ['name', '语言名称'],
                ['sign', '语言标识'],
                ['cover_image', '语言图标','picture'],
                ['is_default', '常用语言','status',['是','否']],
                ['is_use', '是否更新','status','',['未更新','已更新']],
                ['status', '状态', 'switch'],
                ['right_button', '操作', 'btn'],
            ])
            ->addFilter('status',[1=>'启用',0=>'禁用'])
            ->setRowList($data_list)
            ->fetch();
    }

    /**
     * 新增
     * @author 李洪波 <361951119@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['name'] == '' && $this->error('请填写语言名称');
            $data['sign'] == '' && $this->error('请填写语言标识');

            $list = [];
            $list['name']=$data['name'];
            $list['sign']=$data['sign'];
            $list['cover_image']=$data['cover_image'];
            $list['create_time']=date('Y-m-d H:i:s');
            $LanguageModel = new LanguageModel();
            if (false !== $LanguageModel->save($list)) {
                $this->success('新增成功', 'index');
            } else {
                $this->error('新增失败');
            }
        }

        return ZBuilder::make('form')
            ->addFormItems([
                ['text', 'name', '语言名称'],
                ['text', 'sign', '语言标识'],
            ])
            ->addImage('cover_image', '语言图标')
            ->fetch();
    }

    public function edit($id = 0)
    {
        if ($id === 0) $this->error('缺少参数');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');

            // 验证
            $data['name'] == '' && $this->error('请填写语言名称');
            $data['sign'] == '' && $this->error('请填写语言标识');


            if (LanguageModel::update($data,['id'=>$id])) {
                $this->success('编辑成功', 'index');
            } else {
                $this->error('编辑失败');
            }
        }

        // 获取数据
        $info = LanguageModel::get($id);
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->addFormItems([
                ['text', 'name', '语言名称'],
                ['text', 'sign', '语言标识'],
            ])
            ->addImage('cover_image', '语言图标')
            ->setFormData($info)
            ->fetch();
    }

    public function setting(){
        $LanguageModel=new LanguageModel();
        $languages=$LanguageModel->where(['is_use'=>0,'status'=>1])->select();
        if(count($languages)>0){
            foreach ($languages as $language){
                $this->getSql($language);
            }
        }else{
            $this->error('暂无可更新语言');
        }
    }

    private function getSql($language){
        $fields=config('setting.fields');
        foreach ($fields as $table=>$field){
            $sql='';
            $sql.='ALTER TABLE `'.config('database.prefix').$table.'`';
            if($table=='admin_template'){
                //单独处理admin_template
                $tag_num=config('setting.tab_number');
                foreach ($field as $val){
                    for ($i=1;$i<=$tag_num;$i++){
                        $sql.=" ADD COLUMN `".$val[0]."_".$language['sign']."_".$i."` ".$val[1]."(".$val[2].") NOT NULL";
                        if($val['1']!='text'){
                            $sql.=" DEFAULT '',\n";
                        }else{
                            $sql.=",\n";
                        }
                    }
                }
            }else{
                foreach ($field as $val){
                    $sql.=" ADD COLUMN `".$val[0]."_".$language['sign']."` ".$val[1]."(".$val[2].") NOT NULL";
                    if($val['1']!='text'){
                        $sql.=" DEFAULT '',\n";
                    }else{
                        $sql.=",\n";
                    }
                }
            }
            //去除最后一句逗号
            $sql=substr($sql,0,-2);
            $sql.=';';
            Db::execute($sql);
        }

        LanguageModel::update(['is_use'=>1],['id'=>$language['id']]);
        $this->success('更新成功');
    }
}
